<template>
  <div>
    <button type="button" v-on:click="selectFile()" class="btn btn-white btn-default btn-round">
      <i class="ace-icon fa fa-upload"></i>
      {{text}}
    </button>
    <input class="hidden" type="file" ref="file" v-on:change="uploadFile()" v-bind:id="inputId+'-input'">
  </div>
</template>

<script>
  export default {
    name: 'upload',
    props: {
      text: {
        default: "上传文件"
      },
      inputId: {
        default: "file-upload"
      },
      suffixs: {
        default: []
      },
      use: {
        default: ""
      },
      url: {
        default: "upload-file"
      },
      afterUpload: {
        type: Function,
        default: null
      },
    },
    data: function () {
      return {
      }
    },
    methods: {
      uploadFile () {
        let _this = this;
        let file = _this.$refs.file.files[0];

        // 生成文件标识，标识上传的是不是同一个文件
        let key = hex_md5(file.name + file.size + file.type);
        let key10 = parseInt(key, 16);
        let key62 = Tool._10to62(key10);

        // 判断文件格式
        let suffixs = _this.suffixs;
        let fileName = file.name;
        let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
        let validateSuffix = false;
        for (let i = 0; i < suffixs.length; i++) {
          if (suffixs[i].toLowerCase() === suffix) {
            validateSuffix = true;
            break;
          }
        }
        if (!validateSuffix) {
          Toast.warning("文件格式不正确！只支持上传：" + suffixs.join(","));
          // 记得将选择的文件清空
          _this.$refs['file'].value = '';
          // $("#" + _this.inputId + "-input").val("");
          return;
        }

        let param = {
          'use': _this.use,
          'name': file.name,
          'suffix': suffix,
          'size': file.size,
          'key': key62
        };

        _this.upload(param);
      },

      /**
       * 将数据转成base64进行上传
       */
      upload (param) {
        let _this = this;
        let fileShard = _this.$refs.file.files[0];
        // 将图片转为base64进行传输
        let fileReader = new FileReader();

        fileReader.onload = function (e) {
          param.shard = e.target.result;
          _this.$ajax.post(process.env.VUE_APP_SERVER + '/file/admin/' + _this.url, param).then((response) => {
            let resp = response.data;
            Progress.hide();
            _this.afterUpload(resp);
            // 记得将选择的文件清空
            _this.$refs['file'].value = '';
            // $("#" + _this.inputId + "-input").val("");
          });
        };
        fileReader.readAsDataURL(fileShard);
      },

      selectFile () {
        let _this = this;
        $("#" + _this.inputId + "-input").trigger("click");
      }
    }
  }
</script>
